package com.fram.service.api.v1.impl;

import java.math.BigDecimal;
import java.util.List;

import javax.transaction.Transactional;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.fram.bean.api.shopcart.request.ShopCartSearchRequest;
import com.fram.bean.api.shopcart.response.ShopCartSearchResponse;
import com.fram.bean.api.shopcart.response.ShopCartSettlementResponse;
import com.fram.bean.api.user.response.UserAddressSearchResponse;
import com.fram.bean.sys.PageBean;
import com.fram.common.canstant.ErrCode;
import com.fram.common.canstant.PublicConstant;
import com.fram.common.exception.ProAffairException;
import com.fram.common.exception.ProException;
import com.fram.common.exception.ProRunTimeException;
import com.fram.common.exception.ProValiDataException;
import com.fram.common.util.BeanMapper;
import com.fram.entity.OrderShoppingcart;
import com.fram.mapper.OrderShoppingcartMapper;
import com.fram.mapper.UserReceivingAddressMapper;
import com.fram.service.api.v1.ShopCartService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;

/**
 * @作者： 陳曉鬆 @时间： 2020年4月30日 - 上午10:19:29 @description：->
 */
@Service("shopCartService")
public class ShopCartServiceImpl implements ShopCartService {

	@Autowired
	private OrderShoppingcartMapper cartMapper;
	@Autowired
	private UserReceivingAddressMapper userReceivingAddressMapper;

	@Override
	@Transactional
	public void addShopCart(OrderShoppingcart request) throws ProAffairException {
		// 先判断他的购物车是否有这个商品了，如果有的话更改数量
		List<OrderShoppingcart> list = cartMapper.selectForBasicData(BeanMapper.map(request, ShopCartSearchRequest.class));
		if (list == null || list.size() == 0) {// 直接加入购物车
			if (request.getNumber() != 0) {
				if (cartMapper.insertSelective(request) == 0) {
					throw new ProRunTimeException(ErrCode.ORDER_ADD_CART_FAIL.getReturnCode(), ErrCode.ORDER_ADD_CART_FAIL.getReturnMsg());
				}
			}
		} else {
			if (list.size() != 1) {
				throw new ProRunTimeException(ErrCode.ORDER_CART_DATA_FAIL.getReturnCode(), ErrCode.ORDER_CART_DATA_FAIL.getReturnMsg());
			}
			if (request.getNumber() == 0) {
				cartMapper.deleteByPrimaryKey(list.get(0).getId());
			} else {
				if (request.getNumber() + list.get(0).getNumber() <= 0) {
					cartMapper.deleteByPrimaryKey(list.get(0).getId());
				} else {
					// 更改数量
					OrderShoppingcart shoppingcart = new OrderShoppingcart();
					shoppingcart.setId(list.get(0).getId());
					shoppingcart.setNumber(request.getNumber() + list.get(0).getNumber());
					if (cartMapper.updateByPrimaryKeySelective(shoppingcart) == 0) {
						throw new ProRunTimeException(ErrCode.ORDER_ADD_CART_FAIL.getReturnCode(), ErrCode.ORDER_ADD_CART_FAIL.getReturnMsg());
					}
				}
			}
		}
	}

	@Override
	@Transactional
	public PageInfo<ShopCartSearchResponse> updateShopCartNumber(OrderShoppingcart request) throws ProException {
		if (request.getId() == null || request.getDistributorId() == null || request.getNumber() == null) {
			throw new ProRunTimeException(ErrCode.ERR_PARAMETER.getReturnCode(), ErrCode.ERR_PARAMETER.getReturnMsg());
		}
		OrderShoppingcart update = new OrderShoppingcart();
		update.setId(request.getId());
		update.setNumber(request.getNumber());
		if (cartMapper.updateByPrimaryKeySelective(update) == 0) {
			throw new ProRunTimeException(ErrCode.ORDER_UPDATE_CART_FAIL.getReturnCode(), ErrCode.ORDER_UPDATE_CART_FAIL.getReturnMsg());
		}
		PageBean<Long> requestParam = new PageBean<Long>();
		requestParam.setParam(request.getDistributorId());
		return searchShopCartList(requestParam, request.getUserId());
	}

	@Override
	@Transactional
	public void deleteShopCart(List<Long> cartIds) throws ProAffairException {
		if (cartIds == null || cartIds.size() == 0) {
			throw new ProRunTimeException(ErrCode.ERR_PARAMETER.getReturnCode(), ErrCode.ERR_PARAMETER.getReturnMsg());
		}
		if (cartMapper.deleteByIds(cartIds) == 0) {
			throw new ProRunTimeException(ErrCode.ORDER_DELETE_CART_FAIL.getReturnCode(), ErrCode.ORDER_DELETE_CART_FAIL.getReturnMsg());
		}
	}

	@Override
	public PageInfo<ShopCartSearchResponse> searchShopCartList(PageBean<Long> request, Long userId) throws ProException {
		if (request.getParam() == null) {
			throw new ProRunTimeException(ErrCode.ERR_PARAMETER.getReturnCode(), ErrCode.ERR_PARAMETER.getReturnMsg());
		}
		PageHelper.startPage(request.getPageNum(), request.getPageSize());
		List<ShopCartSearchResponse> list = cartMapper.selectForApi(request.getParam(), userId, null);
		if (list == null || list.size() == 0) {
			throw new ProRunTimeException(ErrCode.NO_DATA.getReturnCode(), ErrCode.NO_DATA.getReturnMsg());
		}
		// for (ShopCartSearchResponse response : list) {
		// response.setPrice(response.getPrice().multiply(new BigDecimal(response.getNumber().toString())).setScale(2, BigDecimal.ROUND_HALF_UP));
		// response.setVoucherPrice(response.getVoucherPrice().multiply(new BigDecimal(response.getNumber().toString())).setScale(2, BigDecimal.ROUND_HALF_UP));
		// }
		return new PageInfo<>(list);
	}

	@Override
	public ShopCartSettlementResponse shopCartSettlement(List<Long> cartIds, Long userId) throws ProException {
		ShopCartSettlementResponse response = new ShopCartSettlementResponse();
		// 查询所有商品
		List<ShopCartSearchResponse> cartList = cartMapper.selectForApi(null, null, cartIds);
		if (cartList == null || cartList.size() == 0) {
			throw new ProValiDataException(ErrCode.NO_DATA.getReturnCode(), ErrCode.NO_DATA.getReturnMsg());
		}
		// 判读上下架 剩余量是否能够下单
		/** 商品总金额 **/
		BigDecimal goodsTotalPrice = new BigDecimal("0");
		/** 商品总优惠金额 **/
		BigDecimal goodsTotalVoucherPrice = new BigDecimal("0");
		for (ShopCartSearchResponse cart : cartList) {
			if (cart.getStatus() != PublicConstant.GOODS_STATUS_1) {
				throw new ProValiDataException(ErrCode.FAIL.getReturnCode(), "商品【" + cart.getName() + "】已经下架！无法结算");
			}
			if (cart.getBanlanceNumber() < cart.getNumber()) {
				throw new ProValiDataException(ErrCode.FAIL.getReturnCode(), "商品【" + cart.getName() + "】数量不足！无法结算，剩余数量：" + cart.getBanlanceNumber());
			}
			// 运费取最大值
			if (cart.getLogisticsPrice().doubleValue() > response.getLogisticsPrice().doubleValue()) {
				response.setLogisticsPrice(cart.getLogisticsPrice());
			}
			BigDecimal price = cart.getPrice().multiply(new BigDecimal(cart.getNumber().toString())).setScale(2, BigDecimal.ROUND_HALF_UP);
			BigDecimal voucherPrice = cart.getVoucherPrice().multiply(new BigDecimal(cart.getNumber().toString())).setScale(2, BigDecimal.ROUND_HALF_UP);
			goodsTotalPrice = goodsTotalPrice.add(price).setScale(2, BigDecimal.ROUND_HALF_UP);
			goodsTotalVoucherPrice = goodsTotalVoucherPrice.add(voucherPrice).setScale(2, BigDecimal.ROUND_HALF_UP);
		}
		List<UserAddressSearchResponse> addRessList = userReceivingAddressMapper.selectAddressListByUserId(userId, 1);
		if (addRessList != null && addRessList.size() >= 1) {
			response.setAddress(addRessList.get(0));
		}
		response.setGoodsTotalPrice(goodsTotalPrice);
		response.setGoodsTotalVoucherPrice(goodsTotalVoucherPrice);
		response.setOrderPayPrice(goodsTotalPrice.add(response.getLogisticsPrice()));
		response.setGoodsList(cartList);
		return response;
	}

}
